package com.chms.utility;

import org.apache.log4j.Logger;

public class ApplicationUtil {

	private static final Logger logger = Logger
			.getLogger(ApplicationUtil.class);

	/**
	 * Method to generate new bar code for a product
	 * @param counterVal
	 * @return
	 * @throws ApplicationException
	 */
	public static String getBarCode(String counterVal) throws ApplicationException {
		String barCode = "";
		int generatedVal = 0;
		if (StringUtil.isNullOrEmpty(counterVal)) {
			int incrementalValue = Integer.parseInt(counterVal);
			//if (incrementalValue == 0)
				//generatedVal = incrementalValue;
			//else
				generatedVal = (incrementalValue + 1);
			int digitCount = String.valueOf(generatedVal).length();
			if (ApplicationConstant.BAR_CODE_MAX_DIGIT - (digitCount) >= 0)
				barCode = barCode
						+ getPrefix(ApplicationConstant.BAR_CODE_MAX_DIGIT
								- (digitCount)) + generatedVal;
			else
				throw new ApplicationException(
						ExceptionMessage.TIME_TO_RESET_COUNTER);
		} else
			throw new ApplicationException(ExceptionMessage.INVALID_GENERATOR);
		logger.info("ApplicationUtil: getBarCode()----> Bar code" + barCode);
		return barCode;
	}

	private static String getPrefix(int count) {
		String prefix = "";
		for (int i = 0; i < count; i++)
			prefix = prefix + ApplicationConstant.BAR_CODE_PREFIX;
		return prefix;
	}

	/*
	 * public static void main(String... s) { try { new
	 * ApplicationUtil().getBarCode("0"); new ApplicationUtil().getBarCode("5");
	 * new ApplicationUtil().getBarCode("99999999"); } catch
	 * (ApplicationException ae) { System.out.println(ae.getMessage()); } }
	 */
}
